package com.dyw.blog.utils;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.Json;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * @author Devil
 * @create 2022-02-12 18:56
 */
@Component
public class QiNiuUtil {


    public static final  String url = "http://r76sxd59f.hd-bkt.clouddn.com/";

    //修改以下两个值放到proprietarties中，在密钥管理中获取
    @Value("6hH-N4hXZafmnP5NBueeaCfVYL-iRIoQP_DCX5pf")
    private  String accessKey;
    @Value("4RSIdcJwHGiTwJ3INnrrwDj6AzOKL0zPiasrHLj8")
    private  String accessSecretKey;

    public boolean upload(MultipartFile file,String filename){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huadong());
        //...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String bucket = "dywblog";

        try {
            byte[] uploadBytes = file.getBytes();
            Auth auth = Auth.create(accessKey, accessSecretKey);
            String upToken = auth.uploadToken(bucket);
                Response response = uploadManager.put(uploadBytes, filename, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = JSON.parseObject(response.bodyString(),DefaultPutRet.class);
                return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }


}
